<template>
  <div class="replyContainer">
    <div class="avatar">
      <img v-lazy="replyData.iconPath" />
    </div>
    <div class="content">
      <div class="userInfo" :class="{ chidlrenReplyUserInfo: isChilderen }">
        <span class="userName">{{ userName(replyData) }}</span>
      </div>
      <span
        class="replyContent"
        v-html="showBody"
        v-if="isChilderen"
      ></span>
      <div class="reply">
        <span v-if="!isChilderen">
          <span class="replyTitle">{{replyData.title}}</span>
          <span
            class="replyContent"
            v-html="showBody"
          ></span>
        </span>
        <div class="replyInfo">
          <span class="replytime">{{ changeTime(replyData.createdTime) }}</span>
          <span class="replyBtn" @click="handleReply">回复</span>
          <el-popconfirm title="确认删除此提问吗?" icon="el-icon-info" icon-color="red" class="delteBtn" @confirm="handleRemoveQuestion" v-if="checkIsTeacher && replyData.qid">
            <span slot="reference" >删除</span>
          </el-popconfirm>
          <span class="setAnswer" v-if="isChilderen && isQuestionIssue">设为答案</span>
        </div>
      </div>
    </div>
    <slot />
    <!-- 编辑内容 -->
    <editContent 
      v-if="showEdit && !isChilderen"
      :editId="qid"
      :placeholder="getCurrReplyUserName"
      :menus="['image', 'link']"
      :disabled="!userInfo.userID"
      @confirm="handleSend"
      @uploadImage="uploadImage"
    />
    <div class="endLine" v-if="!isChilderen" />
  </div>
</template>

<script>
import { renderTime, debounce, insertStr } from "@/util/tool";
import { mapState } from "vuex";
import { updateQuestion, deleteQuestion} from "@/request/qAnswer"
import { createReplyData, replyObject } from "./reply";
import { Session } from "@/util/storage/session"
const editContent = () => import("./editContent.vue");
export default {
  components: {
    editContent
  },
  data() {
    return {
      content: "",
    };
  },
  props: {
    parentItem: Object,
    replyData: Object,
    isChilderen: Boolean,
    qid: Number,
    currQid: Number,
    replyUser: Object,
    currNo: Number,
  },
  computed: {
    ...mapState({
      userInfo: (state) => state.user.userInfo,
    }),
    userName() {
      return function (data) {
        return data.authorName || data.realName || data.nickName || data.email || data.regName;
      };
    },
    changeTime() {
      return function (time) {
        return renderTime(time);
      };
    },
    showEdit() {
      return this.replyData.qid
        ? this.currQid === this.replyData.qid
        : this.currQid === this.qid;
    },
    getCurrReplyUserName() {
      return `回复 @${this.userName(this.replyUser) || this.replyUser.userID}:`;
    },
    showBody() {
      return !this.isChilderen ? this.replyData.questionBody : this.replyData.replyBody
    },
    isQuestionIssue() {
      return this.parentItem?.userID == this.userInfo.userID
    },
    checkIsTeacher() {
      let teacher = [2, 32, 128]
      return teacher.filter(item => (item & this.userInfo.roleFlag) === item).length
    }
  },
  methods: {
    handleReply() {
      this.$emit("handleReply", this.replyData.qid || this.qid, this.replyData);
    },
    handleSend(data) {
      let content = data;
      if (this.userInfo.userID !== this.replyUser.userID) {
        content = insertStr(
          content,
          3,
          `回复 <a class="jump-link user" data-user-id="${this.userInfo.userID}" data-reply-id="${this.currQid}">@${this.userName(this.replyUser) || this.replyUser.userID}</a>:`
        );
      }
      const params = JSON.parse(JSON.stringify(this.replyData))
      const replyObj = createReplyData({
        replyBody: content,
        userID: this.userInfo.userID,
        createdTime: new Date().getTime(),
        iconPath: this.userInfo.iconPath,
        realName: this.userInfo.realName || this.userInfo.email || this.userInfo.nickName || this.userInfo.stuNum
      })
      params.replyJson.unshift(replyObj)
      this.removeField(params)
      updateQuestion(params).then((res) => {
        if (res.errno === 0) {
          Session.remove(`/api/curr_question/list?currNo=${this.$route.params.id}`)
          this.replyData.replyJson.unshift(Object.assign(replyObj, this.userInfo))
          this.$antdMessage.success({content: "发表成功"})
          this.$emit("closeEdit")
        } else {
          this.$antdMessage.error({content: res.message || "发表失败"})
        }
      })
    },
    // 移除多余的字段
    removeField(object) {
      const fixedField = Object.keys(replyObject)
      console.log(replyObject);
      Object.keys(object).forEach((key) => {
        if (fixedField.indexOf(key) == -1) {
          object[key] = undefined
        }
      })
    },
    // 删除问答
    handleRemoveQuestion() {
      deleteQuestion({qid: this.replyData.qid}).then((res) => {
        if (res.errno === 0) {
          Session.remove(`/api/curr_question/list?currNo=${this.$route.params.id}`)
          this.$antdMessage.success({content: "已删除!"})
          this.$emit("removeQuestion", this.replyData.qid)
        } else {
          this.$antdMessage.error({content: res.message || "删除失败!"})
        }
      })
    },
    // 上传图片回调
    uploadImage() {
      this.$emit("uploadImage", ...arguments)
    }
  },
  mounted() {
    // 监听鼠标移动到a标签
    // document.addEventListener("mouseover",function(e) {
    //   if (e.target.nodeName === "A") {
    //     console.log(e.target.attributes['data-reply-id'], e.target.attributes['data-user-id']);
    //   }
    // })
    
  }
};
</script>

<style lang="stylus">
.replyContainer {
  position: relative;
  padding: 22px 0 0 80px;

  .avatar {
    position: absolute;
    width: 80px;
    height: 80px;
    left: 0;

    img {
      object-fit: cover;
      position: absolute;
      left: 50%;
      top: 50%;
      transform: translate(-50%, -50%);
      border-radius: 50%;
      // max-width: 48px;
      // max-height: 48px;
      // height: 100%;
      height: 48px;
      width: 48px;
      image-rendering: -webkit-optimize-contrast;
    }
  }

  .content {
    .userInfo {
      display: flex;
      justify-content: flex-start;
      align-items: center;
      margin-bottom: 4px;

      .userName {
        color: #61666d;
        font-size: 13px;
      }
    }

    .chidlrenReplyUserInfo {
      display: inline-block;
      margin-right: 10px;
    }

    .replyTitle {
      font-size: 15px;
      font-weight: bold;
      margin-right: 10px
    }

    .replyContent {
      font-size: 15px;
      padding: 2px 0;

      a {
        color: #008AC5;
      }

      a:hover {
        color: #1890ff
      }
    }

    .reply {
      padding: 2px 0;
    }

    .replyInfo {
      margin-top: 2px
      display: flex;
      align-items: center;
      color: #9499A0;
      font-size: 13px;

      .replytime {
        margin-right: 20px;
      }

      .replyBtn {
        cursor: pointer;
      }

      .setAnswer {
        cursor: pointer;
        margin-left: auto;
        display: none;
      }

      .delteBtn {
        display: none;
        cursor: pointer;
        margin-left: auto
      }
    }
  }

  .replyChildrenList {
    .replyChildren {
      padding: 8px 0 8px 42px;

      .avatar {
        width: 40px;
        height: 40px;

        img {
          max-width: 24px;
          max-height: 24px;
        }
      }

      .delteBtn {
        display: none !important;
        cursor: pointer;
        margin-left: auto
      }
    }

    .replyChildren:hover {
      .setAnswer {
        display: inline-block !important;
      }
      
      .delteBtn {
        display: inline-block !important;
      }
    }

    // .replyContent > p {
    //   display: inline-block;
    // }
  }

  .endLine {
    border-bottom: 1px solid #E3E5E7;
    margin-top: 14px;
  }
}

.replyContainer:hover {
  .delteBtn {
    display: inline-block !important;
  }
}
</style>